import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import { useEffect, useRef, useState } from 'react';
import { useAppDispatch, useAppSelector } from '@/store';
import {
  clearHistoryListAction,
  clearSearchAction,
  getSearchAction,
  setHistoryListAction,
} from '@/store/action/search';
import DOMPurify from 'dompurify';
import { getLocalHistories, removeLocalHistories, setLocalHistories } from '@/utils/storage';
import { uniq } from 'lodash';
import { useSearchHistory } from '@/utils/hooks';
import { useHistory } from 'react-router-dom';
export default function Search() {
  const history = useHistory();
  const {
    suggestList,
    // historyList
  } = useAppSelector((state) => state.search);
  //使用自定义hook
  const { historyList, handleAddHistory, handleClearHistory } = useSearchHistory();

  const searchRef = useRef(-1);
  const dispatch = useAppDispatch();
  const [keyword, setKeyword] = useState('');
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setKeyword(e.target.value);
    // 防抖
    window.clearTimeout(searchRef.current);
    if (e.target.value.trim() === '') {
      dispatch(clearSearchAction());
      return;
    }
    searchRef.current = window.setTimeout(() => {
      dispatch(getSearchAction(e.target.value.trim()));
    }, 500);
  };
  function highLight(keyword: string, result: string) {
    const reg = new RegExp(`(${keyword})`, 'gi');
    return result.replace(reg, `<span>$1</span>`);
  }
  //回车搜索
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      if (keyword.trim() === '') return;
      handleSearch();
    }
  };
  // 点击搜索
  const handleSearch = (str?: string) => {
    // const localHistories = getLocalHistories();
    //存储到redux中 保存搜索历史记录
    //数组去重
    // const newList = [] as string[];
    // [keyword, ...localHistories].forEach((element: string) => {
    //   if (!newList.includes(element)) {
    //     newList.push(element);
    //   }
    // });
    // console.log(newList);
    // dispatch(setHistoryListAction(uniq([keyword, ...localHistories])));
    // setLocalHistories(uniq([keyword, ...localHistories]));
    //使用自定义hook
    handleAddHistory(str || keyword);
    //跳转搜索结果页
    history.push({
      pathname: '/search/result',
      search: `?keyword=${str || keyword}`,
    });
  };
  //清除全部历史记录
  const clearAllHistory = () => {
    // dispatch(clearHistoryListAction());
    // removeLocalHistories();
    handleClearHistory();
  };

  useEffect(() => {
    return () => {
      window.clearTimeout(searchRef.current);
      // 清空搜索结果
      dispatch(clearSearchAction());
    };
  }, []);

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        right={
          <span className="search-text" onClick={() => handleSearch()}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            {/* 输入框 */}
            <input
              onKeyDown={handleKeyDown}
              value={keyword}
              onChange={handleChange}
              type="text"
              placeholder="请输入关键字搜索"
            />

            {/* 清空输入框按钮 */}
            <Icon type="iconbtn_tag_close" className="icon-close" onClick={() => setKeyword('')} />
          </div>
        </div>
      </NavBar>

      {/* 搜索历史 */}
      {!keyword && !!historyList.length && (
        <div className="history" style={{ display: 'block' }}>
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={clearAllHistory}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {historyList.map((item: string, index: number) => {
              return (
                <span key={index} className="history-item" onClick={() => handleSearch(item)}>
                  {item}
                  <span className="divider"></span>
                </span>
              );
            })}
          </div>
        </div>
      )}

      {/* 搜素建议结果列表 */}
      <div className="search-result">
        {suggestList.map((item: string, index: number) => {
          return (
            <div key={index} className="result-item" onClick={() => handleSearch(item)}>
              <Icon className="icon-search" type="iconbtn_search" />
              <div
                className="result-value"
                dangerouslySetInnerHTML={{
                  __html: DOMPurify.sanitize(highLight(keyword, item)),
                }}
              />
            </div>
          );
        })}
      </div>
    </div>
  );
}
